<template>
	<view class="mark-map">
		<view class="title">
			<image :src="user.avatar" class="avatar" @tap="toBuddyList" />
			<view class="btn" @tap="getLoc({flag: 'adr-list'})">
				<icon class="iconfont icon-lvyou"></icon>
				<text class="text">打卡</text>
			</view>
		</view>
		<view class="tools">
			<icon 
				class="iconfont icon-dangqian location" 
				@tap="back2Local(coords,'local')" 
				v-show="mapIsWorking && toolIsWorking">
			</icon>
		</view>
		<map 
			id="mark-map"
			style="width: 100%; height: 100%;" 
			:latitude="coords.lat" 
			:longitude="coords.lng"
			:scale="coords.scale"
			show-location="true"
			@regionchange="mapChange"
			@markertap="markerClick"
			:markers="markers">
		</map>
		<!-- 打卡选择地址 -->
		<uni-popup ref="POP_UP_ADR" mask-background-color="rgba(0,0,0,0)" @tap="popUpAction('')">
			<view v-if="popUpFlag == 'adr-list'" style="height: calc(45vh)">
				<adr-list :coords="coords" @action="adrListDone"></adr-list>
			</view>
		</uni-popup>
		<!-- marker详细内容 -->
		<uni-popup ref="POP_UP_MARKER" mask-background-color="rgba(0,0,0,0)" @tap="popUpAction('')">
			<view v-if="popUpFlag == 'marker-card'">
				<marker-card :data="markerCardData" @action="markerCardDone"></marker-card>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { onMounted, reactive, ref } from "vue"
import { onShow } from "@dcloudio/uni-app"
import request from "../../util/request.js"
import util from "../../util/util.js"
import userInfo from "../../hooks/userInfo.js"
import useWxImg from "../../hooks/useWxImg.js"
import AdrList from "../../components/fun_coms/adrlist.vue"
import MarkerCard from "../../components/fun_coms/markercard.vue"
	export default {
		onShareAppMessage(){
			return {
			  path: '/pages/index/index',
			}
		},
		components: {
			AdrList,
			MarkerCard
		},
		setup() {
			onMounted(()=>{
				login()
				getLoc()
			})
			// user
			let user = userInfo()
			onShow(()=>{
				user.avatar = userInfo().avatar
			})
			// 登陆获取openid
			function login() {
				uni.login({
					success: async (res) => {
						// console.log(res)
						let r = await request.login(res)
						if (r.code == 10000) {
							let _data0 = r.data[0]
							let _data1 = r.data[1]
							user.IDNumber = _data0._id
							user.openId = _data0.openId
							user.name = _data0.name
							user.avatar = _data0.avatar || '/static/imgs/nouser.png'
							user.session_key = _data1.session_key
							uni.setStorageSync('token',_data1.token)
							setMarkMap()
							setTimeout(function() {
								request.getInfo(user.openId)
							}, 3000);
						}
					},
					fail: (err) => {
						console.log(err)
					},
				})
			}
			// 获取当前坐标
			let mapctx = uni.createMapContext('mark-map',this)		
			let coords = reactive({
				lat: 41.769465,
				lng: 123.427158,
				scale: 14,
			})
			let mapIsWorking = ref(false)
			function getLoc(e = {}) {
				// console.log(e)
				uni.showLoading({
					title: '获取当前位置…'
				})
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						// console.log(res)
						coords.lat = res.latitude
						coords.lng = res.longitude
						mapIsWorking.value = true
						if (e.flag && e.flag == 'adr-list') {
							popUpAction(e.flag)
						}
						uni.hideLoading()
					},
					fail: (err) => {
						console.log(err)
						uni.hideLoading()
						uni.showModal({
							title: '允许小程序获取位置',
							content: '签到功能需要使用位置消息',
							success: function (res) {
								if (res.confirm) {
									openSet()
								} else if (res.cancel) {
									mapIsWorking.value = false
									uni.showToast({
										title: '如需使用签到功能，请允许位置消息',
										icon: "none",
										duration: 2500
									})
								}
							}
						});
					}
				})
			}
			// 跳转到小程序设置页面
			function openSet() {
				uni.openSetting({
				  success: (res) =>{
						// console.log(res)
						getLoc()
					},
					fail: (err) => {
						console.log(err)
					},
				})
			}
			// 获取今日打卡mark
			let markers = ref()
			async function setMarkMap() {
				let g = {}
				g.openId = user.openId
				g.sTime = util.formatDate(new Date(), '-')+' 00:00:00'
				g.eTime = util.formatDate(new Date(), '-')+' 23:59:59'
				let r = await request.getMarks(g)
				if (r.code == 10000) {
					let _data = r.data
					let _markers = []
					for (let i in _data) {
						let m = {}
						m.recId = _data[i]._id
						m.id = i*1+1
						m.latitude = _data[i].latitude
						m.longitude = _data[i].longitude
						m.title = _data[i].title
						m.adress = _data[i].address
						m.iconPath = '/static/imgs/marker.png'
						m.width = 42
						m.height = 42
						m.callout = {}
						_markers.push(m)
					}
					markers.value = _markers
				}
			}
			// 地图变化
			let toolIsWorking = ref(false)
			function mapChange(e) {
				// console.log(e.causedBy,toolIsWorking.value)
				if (!e.causedBy || 'upudate,update'.indexOf(e.causedBy) >= 0) return
				mapctx.getCenterLocation({
					success: (res) => {
						// console.log(res)
						if (Math.abs(res.latitude - coords.lat) > 0.001 || Math.abs(res.longitude - coords.lng) > 0.001) {
							toolIsWorking.value = true
						} else {
							toolIsWorking.value = false
						}
					},
					fail: (err) => {
						console.log(err)
					}
				})
			}
			// 点击marker
			function markerClick(e) {
				let _id = e.markerId
				let _markers = markers.value
				let marker = null
				for(let i in _markers) {
					if (_id == _markers[i].id) {
						marker = _markers[i]
					}
				}
				if (marker.latitude && marker.longitude) {
					mapctx.moveToLocation({
						latitude: marker.latitude,
						longitude: marker.longitude,
						success: (res) => {
							if (_id == 0) {
								return
							}
							getMarksDetail(marker)
						},
						fail: (err) => {
							console.log(err)
						}
					})
				}
			}
			// 定位到坐标位置
			function back2Local(local,flag) {
				let _lat = flag == 'select' ? local.location.lat : local.lat
				let _lng = flag == 'select' ? local.location.lng : local.lng
				mapctx.moveToLocation({ 
					latitude: _lat,
					longitude: _lng,
					success: (res) => {
						// console.log(res)
						delMarker(0)
						if (flag == 'local') {
							toolIsWorking.value = false
						} else if (flag == 'select') {
							let m = {}
							m.id = 0
							m.latitude = _lat
							m.longitude = _lng
							m.width = 30
							m.height = 42
							m.title = local.title
							m.address = local.address
							markers.value.push(m)
							m.markerId = m.id
							toolIsWorking.value = true
						}
					},
					fail: (err) => {
						console.log(err)
					}
				})
			}
			// 删除某个marker
			function delMarker(index) {
				let _markers = markers.value
				for (let i in _markers) {
					if (_markers[i].markerId == index) {
						_markers.splice(i,1)
					}
				}
				markers.value = _markers
			}
			// 查询marker明细数据
			async function getMarksDetail(m) {
				let _markers = markers.value
				let recIds = []
				for (let i in _markers) {
					if (m.latitude == _markers[i].latitude && m.longitude == _markers[i].longitude) {
						recIds.push(_markers[i].recId)
					}
				}
				let g = {}
				g.openId = user.openId
				g.recIds = JSON.stringify(recIds)
				let r = await request.getMarksById(g)
				if (r.code == 10000) {
					markerCardData.markers = r.data
					markerCardData.flag = 'marker'
					popUpAction('marker-card')
				}
			}
			// 打卡定位及marker操作
			let POP_UP_ADR = ref(null)
			let POP_UP_MARKER = ref(null)
			let popUpFlag = ref('')
			function popUpAction(f) {
				delMarker(0)
				if (f == 'adr-list') {
					POP_UP_MARKER.value.close()
					popUpFlag.value = f
					POP_UP_ADR.value.open('bottom')
				} else if (f == 'marker-card') {
					POP_UP_ADR.value.close()
					popUpFlag.value = f
					POP_UP_MARKER.value.open('top')
				} else {
					POP_UP_ADR.value.close()
					POP_UP_MARKER.value.close()
					setTimeout(function() {
						popUpFlag.value = ''
					}, 150);
				}
			}
			// 选择打卡地址
			function adrListDone(e) {
				if (e.flag == 'select') {
					back2Local(e,e.flag)
				} else if (e.flag == 'done') {
					markerCardData.markers = e
					markerCardData.flag = 'mark'
					popUpAction('marker-card')
				} else {
					popUpAction('')
				}
			}
			// markerCard数据
			let markerCardData = reactive({
				marker: {}, 
				marks: [], 
				flag: ''
			})
			// 增加或删除marker后的处理
			function markerCardDone(e) {
				delMarker(0)
				let _markers = markers.value
				if (e.recId) {
					// 删除
					for(let i in _markers) {
						if (e.recId == _markers[i].recId) {
							if (e.popUpAction == 'del-img') {
								markers.value[i].img = ''
							} else {
								markers.value.splice(i,1)
							}
						}
					}
				} else {
					// 新增					
					let m = {}
					m.recId = e._id
					m.id = markers.value.length*1+1
					m.latitude = e.latitude
					m.longitude = e.longitude
					m.title = e.title
					m.adress = e.address
					m.iconPath = '/static/imgs/marker.png'
					m.width = 42
					m.height = 42
					m.callout = {}
					markers.value.push(m)
				}
				if (e.popUpAction == 'close') popUpAction('')
			}
			
			// 查看朋友列表		
			async function toBuddyList() {
				uni.navigateTo({
					url:'/pages/buddy/buddy'
				})
			}
			
			// 是否为空
			function isNull(s) {
				return util.isNull(s)
			}
			
			return {
				user,login,getLoc,
				coords,markers,markerClick,mapChange,
				mapIsWorking,toolIsWorking,back2Local,
				POP_UP_ADR,POP_UP_MARKER,popUpFlag,popUpAction,
				adrListDone,markerCardData,markerCardDone,
				toBuddyList,isNull
			}
		}
	}
</script>

<style lang="scss" src="./index.scss"></style>